<?php


namespace api\home\controller;


use api\home\model\UserModel;
use cmf\controller\RestBaseController;
use think\facade\Db;
use think\Request;


class MoneyController extends RestBaseController
{
    public function createMoney(Request $request)
    {
        $money = input('money/f','');

        if(!$money){
            $this->error('请输入金额');
        }
        $user = UserModel::find($request->userId);
        if(!$user){
            $this->error('参数错误');
        }

        //计算新余额
        $after = $user['wallet'] + $money;
        //$res = money_log($request->userId,$money,$user['wallet'],$after,'1');

        //事务
        Db::startTrans();
        try {
            $res = money_log($request->userId,$money,$user['wallet'],$after,'1');

            $log = UserModel::where('id','=',$request->userId)->update(['wallet' => $after]);
        } catch (\Exception $exception) {
            //回滚事务
            Db::rollback();
        }
        if($res && $log) {
            //提交事务
            Db::commit();
            $this->success('充值成功');
        }else{
            //回滚事务
            Db::rollback();
            $this->error('充值失败');
        }
    }
}